/**
 * @Time: 2018/11/22 13:55
 * @Author: wangmin
 * @File: object
 * @Software: GoLand
 */
package object

import (
	"github.com/astaxie/beego/orm"
	"open_manjing/oss/models"
	"errors"
	"os"
)

//对象模型
type Object struct {
	models.App
}

//删除对象
func (m *Object) Remove(id int) error {
	if !m.Ormer.QueryTable("Object").Filter("Id", id).Exist() {
		return errors.New("对象不存在")
	}
	m.Ormer.QueryTable("Object").Filter("Id", id).Update(orm.Params{
		"IsDel": 1,
	})
	return nil
}

//回收资源
func (m *Object) Recycling(id int) error {
	object := &models.Object{}
	err := m.Ormer.QueryTable("Object").Filter("Id", id).One(object, "IsDel", "Path")
	switch err {
	case nil:
		if object.IsDel != 1 {
			return errors.New("对象非删除状态无法回收资源")
		}
		if object.Path != "" {
			_, err := os.Stat(object.Path)
			if err == nil || os.IsExist(err) {
				err = os.Remove(object.Path)
				if err != nil {
					return err
				}
			} else {
				return err
			}
		}
		m.Ormer.QueryTable("Object").Filter("Id", id).Delete()
		return nil
	case orm.ErrNoRows:
		return nil
	default:
		return err
	}

}

//Instance
func Instance(o orm.Ormer) *Object {
	i := &Object{
	}
	i.Ormer = o
	return i
}
